<?php
namespace jy_guashop;
defined('BY_JYA') or exit('error');
/*
	分销插件会员类
	如果将分销商各项数据在每次数据变动时计算好并存入数据库。
	那么分别需要做
		在设置上下级关系时，修改新上级的 下线数量、分销商数量、订单数量、订单收益数量等数据
		在变更上下级关系时，修改原、新上级的各项参数
		在发生订单时，修改上级的订单相关参数
		在用户成为分销商时，修改上级的分销商数量相关数据
*/
class team extends \plugin{
	/*
		核实分销商
	*/
	public function checkmember($mid=0,$isexi=false){
			$mid=$mid?:$_SESSION['uid'];
			$member=$this->get('member',array('mid'=>$mid,'uniacid'=>$_SESSION['uniacid']));
			$teampage=$this->plugin_setting('teampage');
			$this->teamsetting=$this->plugin_setting('teamsetting');
			$teampage['tagent']=$teampage['tagent']?:'团长';
			if(!$member['is_agent']){
				$apply=$this->get('member',array('mid'=>$_SESSION['uid']),array('id','apply_status'));
				if($apply['id'] && $apply['apply_status']==3){
					if($isexi){
						exi('申请正在审核请耐心等待','error','jy_guashop/team.apply/');
					}else{
						return false;
					}
				}
				$member['can_apply']=false;
				//如果成为分销商无条件，此处自动申请成为分销商
				if($this->teamsetting['become']==0){
					//分销商无需审核，此处自动审核
					$member['can_apply']=true;
					$this->apply_agent($member['mid']);
					if($this->teamsetting['isshenhe'] && $isexi){
						exi('申请正在审核请耐心等待','error','jy_guashop/team.apply/');
					}else{
						exi('','','jy_guashop/team.index/');
					}
				}elseif($this->teamsetting['become']==3){
						//参与挂卖
						$iscan=pdo_count('jy_guashop_canlog',array('ispay'=>1,'mid'=>$mid));
						$member['desc']='参与挂卖后';
						if($iscan){
							$member['can_apply']=true;
							$this->apply_agent($member['mid']);
							$ispass=true;
						}
				}elseif($this->teamsetting['become']==4){
						//自购订单总金额
						$buyfee=pdo_getsum('jy_weishop_order',array('ispay'=>1,'mid'=>$mid,'uniacid'=>$_SESSION['uniacid']),'price');
						$buyfee=$buyfee?:0;
						$member['now']=$buyfee;
						$member['limit']=$this->teamsetting['buyallfee'];
						$member['unit']='元';
						if($buyfee>=$this->teamsetting['buyallfee']){
							$member['can_apply']=true;
							$this->apply_agent($member['mid']);
							$ispass=true;
						}
				}elseif($this->teamsetting['become']==5){
						//购买指定商品
						$become_goods=$this->teamsetting['become_goods'];
						$member['become_goods']=$become_goods;
						foreach($become_goods as &$bgv){
							$isbuy=pdo_count('jy_weishop_order_goods',array('mid'=>$member['mid'],'goodsid'=>$bgv['id'],'ispay'=>1));
							if($isbuy>0){
								$member['can_apply']=true;
								$this->apply_agent($member['mid']);
								$ispass=true;
								break;
							}
						}
				}elseif($this->teamsetting['become']==2){
					$member['can_apply']=true;
					if($isexi){
						exi('你还不是'.$teampage['tagent'].'，请前往申请！','error','jy_guashop/team.apply/');
					}
				}elseif($this->teamsetting['become']==1){
					$member['desc']='暂时无法申请，只能由管理员后台指定';
				}
				if($this->teamsetting['isshenhe'] && $isexi && $ispass){
						exi('申请正在审核请耐心等待','error','jy_guashop/team.apply/');
				}elseif($ispass){
						$team=$this->get('member',array('mid'=>$_SESSION['uid']),array('id','status'));
						if($team['status']){
							exi('','','jy_guashop/team.index/');
						}
				}
				if($isexi){
						exi('你还不是'.$teampage['tagent'].'，请前往申请！','error','jy_guashop/team.apply/');
				}
			}elseif($member['stop'] && $isexi){
				exi('你的'.$teampage['tagent'].'身份已禁用！','error','jy_guashop/team.apply/');
			}elseif((!$member['realname'] || !$member['mobile']) && $isexi){
				$newmember=$this->get('member',array('mid'=>$member['mid'],'uniacid'=>$_SESSION['uniacid']));
				if($this->teamsetting['isinfo']==1 && (!$newmember['realname'] || !$newmember['mobile'])){
					exi('请先完善信息','error','jy_guashop/team.info/');
				}else{
					
				}
			}
			return $member;
	}
	public function member_update($mid,$update=array()){
		pdo_update('jy_guashop_member',$update,array('mid'=>$mid));
		return true;
	}
	/*
		申请成为团队长
	*/
	public function apply_agent($mid,$area_code=''){
		$mid=$mid?:$_SESSION['uid'];
		$team=$this->get('member',array('uniacid'=>$_SESSION['uniacid'],'mid'=>$mid));
		if($team['id'] && $team['apply_status']==1){
			exi('您的申请已经通过！','error','jy_guashop/team.index/');
		}elseif($team['id'] && $team['apply_status']==3){
			exi('您已经申请了团长！','error','jy_guashop/team.apply/');
		}
		if($team['id']){
			$new_apply=array(
				'apply_status'=>3,
			);
			$this->update('member',$new_apply,array('uniacid'=>$_SESSION['uniacid'],'mid'=>$mid));
			$id=$team['id'];
		}else{
			$fromuser=pdo_getcolumn('jy_guashop_member',array('mid'=>$mid,'uniacid'=>$_SESSION['uniacid']),'fromuser');
			$new_apply=array(
				'uniacid'=>$_SESSION['uniacid'],
				'mid'=>$mid,
				'apply_status'=>3,
				'fromuser'=>$fromuser?:$_SESSION['fromuser'],
				'createtime'=>TIMESTAMP,
			);
			pdo_insert('jy_guashop_member',$new_apply);
			$this->update_agent_level($mid);
			$id=pdo_insertid();
		}
		$this->teamsetting=$this->plugin_setting('teamsetting');
		if(!$this->teamsetting['isshenhe']){
			//分销商无需审核，此处自动审核
			$this->check_agent($id,1);
		}
		return $id;
	}
	/*
		审核团队长
	*/
	public function check_agent($agent_id,$status,$remark=''){
		if(!$agent_id){
			return;
		}
		$agent_area=$this->get('member',array('id'=>$agent_id));
		if(!$agent_area){
			return;
		}
		$update=array(
			'apply_status'=>$status,
		);
		if($update['apply_status']==1){
			$update['is_agent']=1;
			$this->update_agent_level($agent_area['fromuser']);
		}else{
			$update['apply_msg']=$remark;
		}
		$this->update('member',$update,array('id'=>$agent_id));
		return true;
	}
	public function set_parent($mid,$fromuser=0){
		$mid=$mid?:$_SESSION['uid'];
		if($mid==$fromuser || !$fromuser){
			return false;
		}
		//如果他的上级是我
        $ta_agent_id=$this->getcolumn('member',array('mid'=>$fromuser),'fromuser');
		if($ta_agent_id==$mid){
			return true;
		}
		$this->update('member',array('fromuser'=>$fromuser,'updatetime'=>TIMESTAMP),array('mid'=>$mid));
		$this->update_agent_level($fromuser);
		return true;
	}
	/*
		禁用团长
	*/
	public function stop_agent($agent_id){
		$this->update('member',array('stop'=>1),array('mid'=>$agent_id));
	}
	/*
		恢复团长
	*/
	public function start_agent($agent_id){
		$this->update('member',array('stop'=>0),array('mid'=>$agent_id));
	}

	/*
		升级分销商等级
		先检测会员身份是否为正常分销商
		然后获取分销商当前等级的下一等级升级条件
		然后逐个条件对比，看是否满足升级条件
		如果全部满足，则升级到相应等级
		
		何时触发升级分销商等级检测呢？
		
	*/
	public function update_agent_level($mid,$self=false){
		//
		if(!$mid){
			return;
		}
		$agent=$this->get('member',array('mid'=>$mid));
		if(!$agent['mid']){
			return;
		}
		if($agent['is_agent']!=1 && !$self){
			return;
		}
		$level=$this->get('teamlevel',array('id'=>$agent['level_id']));
		$level['level']=$level['level']?:0;
		$level_up_types=$this->model('model')->team_level_up_types();//获取当前设置的分销商等级升级条件
		if(!$level_up_types){
			return;
		}
		$levels=$this->getall('teamlevel',array('uniacid'=>$_SESSION['uniacid'],'level >'=>$level['level']),'','','level desc');
		if(empty($levels)){
			return;
		}
		$teamids=$this->getteamids($agent['mid'],2);
		if(!$teamids){
			$teamids=-1;
		}
		foreach($levels as $lv){
			$conditions=json_decode($lv['conditions'],true);
			if(!$level_up_types || !$lv['id']){
				break;
			}
			$up=true;
			foreach($level_up_types as $type){
			    //file_put_contents(ROOT_D.'/4.txt',$agent['mid'].'~~'.$type."\n",FILE_APPEND);
				if($type=='myorder_price'){
					//自购N元
					$agent['myorder_price']=pdo_getsum('jy_weishop_order',array('uniacid'=>$_SESSION['uniacid'],'ispay'=>1,'mid'=>$agent['mid']),'price');
					if($agent['myorder_price']<$conditions['myorder_price'] && $conditions['myorder_price']){
						//file_put_contents(ROOT_D.'/4.txt',$type."\n",FILE_APPEND);
						$up=false;
						break;
					}
				}elseif($type=='zhi_num'){
					//直推同等级人数
					$agent['zhi_num']=pdo_count('jy_guashop_member',array('uniacid'=>$_SESSION['uniacid'],'level_id'=>$agent['level_id'],'fromuser'=>$agent['mid']));
					if($agent['zhi_num']<$conditions['zhi_num'] && $conditions['zhi_num']){
						//file_put_contents(ROOT_D.'/4.txt',$agent['mid'].'~~'.$agent['zhi_num']."zhi_num\n",FILE_APPEND);
						$up=false;
						break;
					}
				}elseif($type=='jian_num'){
					//间推同等级人数
                    $teamids=$this->getall('member',array('uniacid'=>$_SESSION['uniacid'],'fromuser'=>$agent['mid']),array('mid'),'mid');
                    if($teamids){
                        $teamids=array_keys($teamids);
                    }else{
                        $teamids=-1;
                    }
					$agent['jian_num']=pdo_count('jy_guashop_member',array('uniacid'=>$_SESSION['uniacid'],'level_id'=>$agent['level_id'],'fromuser'=>$teamids));
					if($agent['jian_num']<$conditions['jian_num'] && $conditions['jian_num']){
                       //file_put_contents(ROOT_D.'/4.txt',$agent['mid'].'~~'.$agent['jian_num']."jian_num\n",FILE_APPEND);
						$up=false;
						break;
					}
				}elseif($type=='team_fee'){
					//直推获得N能量值
					$agent['team_fee']=pdo_getsum('jy_guashop_commission',array('type'=>1,'uniacid'=>$_SESSION['uniacid'],'mid'=>$teamids),'jifen');
					if($agent['team_fee']<$conditions['team_fee'] && $conditions['team_fee']){
						//file_put_contents(ROOT_D.'/4.txt',$type."\n",FILE_APPEND);
						$up=false;
						break;
					}
				}elseif($type=='isget_jifen'){
                    //自购获得多少积分
                    $agent['isget_jifen']=pdo_getsum('core_credit_log',array('plugin'=>'jy_weishop','type'=>1,'is_add'=>1,'uniacid'=>$_SESSION['uniacid'],'mid'=>$agent['mid']),'fee');
                    if($agent['isget_jifen']<$conditions['isget_jifen'] && $conditions['isget_jifen']){
                        //file_put_contents(ROOT_D.'/4.txt',$type."\n",FILE_APPEND);
                        $up=false;
                        break;
                    }
                }elseif($type=='teamget_jifen'){
                    //直推获得多少积分
                    $agent['teamget_jifen']=pdo_getsum('core_credit_log',array('plugin'=>'jy_weishop','type'=>1,'is_add'=>1,'uniacid'=>$_SESSION['uniacid'],'mid'=>$teamids),'fee');
                    if($agent['teamget_jifen']<$conditions['teamget_jifen'] && $conditions['teamget_jifen']){
                        //file_put_contents(ROOT_D.'/4.txt',$type."\n",FILE_APPEND);
                        $up=false;
                        break;
                    }
                }
			}
			if($up){
				$next_level=$lv;
				break;
			}
		}
		if($up){
				$update=array(
					'level_id'=>$next_level['id'],
					'status'=>1,
				);
				$this->update('member',$update,array('id'=>$agent['id']));
				$this->model('commission')->uplevel_per($agent);
				$this->update_agent_level($agent['fromuser']);
		}
		return true;
	}
	
	public function getteamids($teammid,$level=12){
		$newmembers=array();
		$newteammids=$teammid;
		for($i=1;$i<$level;$i++){
			$members=$this->getall('member',array('uniacid'=>$_SESSION['uniacid'],'fromuser'=>$newteammids),array('mid'),'mid');
			if($members){
				foreach($members as $key=>$item){
					$newmembers[$key]=$key;
				}
				$newteammids=array_keys($members);
			}else{
				break;
			}
		}
		if($newmembers){
			$teamids=array_keys($newmembers);
		}else{
			$teamids=array();
		}
		return $teamids;
	}
}